<template>
  <el-dialog :visible.sync="dialog" :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="600px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="70px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="登陆名" prop="username">
            <el-input v-model="form.username" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="状态" prop="enabled">
            <el-radio v-for="item in dicts" :key="item.id" v-model="form.enabled" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model.number="form.phone" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="dept.id">
            <treeselect
              v-model="form.dept.id"
              :options="depts"
              :style="style"
              placeholder="选择部门"
              @select="selectFun"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="岗位" prop="job.id">
        <el-select v-model="form.job.id" :style="style" placeholder="请选择岗位" @change="selectJobId">
          <el-option
            v-for="(item, index) in jobs"
            :key="item.name + index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px;" label="角色" prop="roles">
        <el-select
          v-model="roleIds"
          style="width: 480px;"
          multiple
          placeholder="请选择"
          @change="selectRole"
        >
          <el-option
            v-for="(item, index) in roles"
            :key="item.name + index"
            :disabled="level !== 1 && item.level <= level"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { add, edit } from '@/api/user'
import { getDepts } from '@/api/dept'
import { getAll, getLevel } from '@/api/role'
import { getAllJob } from '@/api/job'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { isvalidPhone } from '@/utils/validate'

export default {
  components: { Treeselect },
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    },
    dicts: {
      type: Array,
      required: true
    }
  },
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    const validRoles = (rule, value, callback) => {
      console.log(value, '......')
      if (!value || value.length === 0) {
        callback(new Error('请选择角色'))
      } else {
        callback()
      }
    }

    return {
      dialog: false,
      loading: false,
      form: { username: '', name: '', email: '', enabled: 'true', roles: [], job: { id: '' }, dept: { id: '' }, phone: null },
      roleIds: [],
      roles: [],
      depts: [],
      jobs: [],
      deptId: null,
      jobId: null,
      style: 'width: 184px',
      level: 3,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        enabled: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
        roles: [
          { required: true, message: '角色不能为空', trigger: 'blur', validator: validRoles }
        ],
        'job.id': [
          { required: true, message: '岗位不能为空', trigger: 'blur' }
        ],
        'dept.id': [
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    const explorer = navigator.userAgent
    if (explorer.indexOf('Chrome') >= 0) {
      this.style = 'width: 184px'
    } else {
      this.style = 'width: 172px'
    }
  },
  methods: {
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.form.dept.id = this.deptId
      this.form.job.id = this.jobId
      this.form.roles = []
      const _this = this
      this.roleIds.forEach(function(data, index) {
        const role = { id: data }
        _this.form.roles.push(role)
      })

      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else this.doEdit()
        } else {
          return false
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          message: '默认密码：123456',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.deptId = null
      this.jobId = null
      this.roleIds = []
      this.form = { username: '', name: '', email: '', enabled: 'false', roles: [], job: { id: '' }, dept: { id: '' }, phone: null }
    },
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(err => {
        console.log(err)
      })
    },
    getJobs(id) {
      console.log(id)
      this.jobId = null
      this.form.job.id = null
      this.jobs = []
      getAllJob(id).then(res => {
        this.jobs = res.content
      }).catch(err => {
        console.log(err)
      })
    },
    getDepts() {
      console.log(this, this.form)
      this.deptId = null
      this.form.dept.id = null
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content
      })
    },
    selectFun(node) {
      this.deptId = node.id
      this.form.dept.id = node.id
      this.getJobs(node.id)
    },
    selectJobId(node) {
      this.jobId = node
      this.form.job.id = node
    },
    selectRole(node) {
      console.log(node, this.roleIds)
      this.form.roles = []
      const _this = this
      this.roleIds.forEach(function(data, index) {
        const role = { id: data }
        _this.form.roles.push(role)
      })
      console.log(this.form.roles)
    },
    getRoleLevel() {
      getLevel().then(res => {
        console.log(res)
        this.level = res.level
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>

<style scoped>

</style>
